package at.punkt.repository.talis;

import java.io.File;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLParser;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;

/**
 * Implementation of the {@link Repository} interface for Talis.
 *
 * @author Alexander Kreiser
 * @author Jürgen Jakobitsch
 */
public class TalisRepository implements Repository {

    protected final String _baseUrl;
    protected File _dataDir;
    protected boolean _initialized = false;
    protected final ValueFactory _factory = new ValueFactoryImpl();

    protected HttpClient _client;
    private Credentials _credentials;
    private SPARQLResultsXMLParser _SPARQLResultsXMLParser;

    public TalisRepository(String serviceBaseUrl, String user, String pass) {
        _baseUrl = serviceBaseUrl;
        _credentials = new UsernamePasswordCredentials(user, pass);
        //_client = new TalisClient(this);
        _client = new HttpClient();
        _client.getState().setCredentials( AuthScope.ANY, _credentials );
        _SPARQLResultsXMLParser = new SPARQLResultsXMLParser();
    }

    public void setDataDir(File arg0) {
        _dataDir = arg0;
    }

    public File getDataDir() {
        return _dataDir;
    }

    public void initialize() throws RepositoryException {
        _initialized = true;
    }

    public void shutDown() throws RepositoryException {
        _initialized = false;
    }

    public boolean isWritable() throws RepositoryException {
        if (!_initialized) {
            throw new IllegalStateException("HTTPRepository not initialized.");
        }
        return true;
    }

    public RepositoryConnection getConnection() throws RepositoryException {
        final TalisConnection con = new TalisConnection(this, _client);
        return con;
    }

    public ValueFactory getValueFactory() {
        return _factory;
    }

    String getRepositoryUrl() {
        return _baseUrl;
    }

    public SPARQLResultsXMLParser getSPARQLResultsXMLParser(){        
        return this._SPARQLResultsXMLParser;
    }
}